package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
	redis2 "github.com/gomodule/redigo/redis"
	"net/http"
	"news/global"
	"news/initialize"
	"news/middleware"
	"news/models"
	"news/utils"
	"strconv"
	"strings"
	"time"
)

type MyCustomClaims struct {
	Foo string `json:"foo"`
	jwt.StandardClaims
}

// Check 检测权限是否认证
func Check(c *gin.Context) {
	middleware.Check()
	str := fmt.Sprintf("%v", global.User)
	explode := strings.Split(str, "\\")
	var user models.Users
	global.DB.Where("id =?", explode[1]).First(&user)
	user.PassWord = ""
	c.JSON(http.StatusOK, gin.H{
		"ok":    true,
		"users": user,
	})
}

// Login 用户登录
func Login(c *gin.Context) {
	name := c.PostForm("name")
	password := c.PostForm("password")

	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"data": "请输入用户名"})
		return
	}
	if password == "" {
		c.JSON(http.StatusBadRequest, gin.H{"data": "请输入密码"})
		return
	}
	newPass := utils.Md5(password)
	//检测用户
	var user models.Users
	if err := global.DB.Model(&models.Users{}).Where("user_name=?", name).Where("pass_word=?", newPass).Find(&user); err.RowsAffected == 0 {
		c.JSON(http.StatusForbidden, gin.H{"data": "用户未找到或者密码错误！"})
		return
	}
	// Create the Claims
	claims := MyCustomClaims{
		"bar",
		jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 60*60*24*30,                   //30天过期
			Issuer:    user.UserName + "\\" + strconv.Itoa(int(user.ID)), //携带用户id
		},
	}
	//jwt:头部（header） 有效载荷（Payload） 签名（signature）组成
	//jwt加密,HS256算法
	var mySign = []byte(global.Config.JWTInfo.SigningKey)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokens, err := token.SignedString(mySign)

	if err != nil {
		//这里生成日志
		panic(err)
	}
	//返回json数据
	c.JSON(http.StatusOK, gin.H{
		"data": map[string]interface{}{
			"user_name": user.UserName,
			"token":     tokens,
		},
	})
}

type Site struct {
	Count1 int `json:"count1"`
	Count2 int `json:"count2"`
}

// Info 网站数据统计
func Info(c *gin.Context) {
	Redis := initialize.RedisConnect()
	//redis读取统计信息
	count1, _ := redis2.Int(Redis.Do("HGet", global.WebsiteIndex, "count1"))
	count2, _ := redis2.Int(Redis.Do("HGet", global.WebsiteIndex, "count2"))
	c.JSON(http.StatusOK, gin.H{
		"count1": count1,
		"count2": count2,
	})
}
